package net.chasing.androidbaseconfig.util;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

/**
 * 时间日期相关的工具类
 * 服务器有时返回格式 'yyyy-MM-dd'  有时'yyyy/MM/dd'
 * 所以为了复用及避免出错，建议在每个方法开始时将 '-'('/')转换成'/'('-')进行操作
 */
@SuppressLint("SimpleDateFormat")
public class TimeUtils {

    public static final int MIN_YEAR = 1970;
    public static final int MAX_YEAR = 2099;
    public static final String MIN_DATE_TIME = "1970-01-01";
    public static final String MAX_DATE_TIME = "2099-12-31";

    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy/MM/dd HH:mm:ss";
    public static final String YYYY_MM_DD_HH_MM = "yyyy/MM/dd HH:mm";
    public static final String YYYY_MM_DD_E_HH_MM = "yyyy/MM/dd E HH:mm";  // E 代表 周一 到 周日
    public static final String MM_DD_E_HH_MM = "MM/dd E HH:mm";  // E 代表 周一 到 周日
    public static final String MM_DD_E = "MM/dd E";  // E 代表 周一 到 周日
    public static final String YYYY_MM_DD = "yyyy/MM/dd";
    public static final String HH_MM = "HH:mm";

    private TimeUtils() {
    }

    // region 获取、判断

    /**
     * 获取当前24小时制的时间  yyyy/MM/dd HH:mm:ss
     * 注意：模拟器只能获取到12小时制的时间
     */
    public static String getCurrentDateTime() {
        return getCurrentDateTime(YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 根据格式获取当前时间
     * 注意：模拟器只能获取到12小时制的时间
     */
    public static String getCurrentDateTime(String format) {
        return long2String(System.currentTimeMillis(), format);
    }

    /**
     * 获取当天日期 2021/05/19
     */
    public static String getCurrentDate() {
        return long2String(System.currentTimeMillis(), YYYY_MM_DD);
    }

    public static String getCurrentDate(String format) {
        return long2String(System.currentTimeMillis(), format);
    }

    /**
     * 获取当天的信息
     *
     * @return int[7]
     * 0：年
     * 1：月
     * 2：日
     * 3：时
     * 4：分
     * 5：秒
     * 6：周几
     */
    public static int[] getCurrentDayInfo() {
        return getDayInfo(getCurrentDateTime());
    }

    //获取今年年份
    public static int getCurrentYear() {
        return Integer.parseInt(long2String(System.currentTimeMillis(), "yyyy"));
    }

    //根据指定的年月日生成合法的日期字符串
    @SuppressLint("DefaultLocale")
    public static String getLegalStrTime(int year, int month, int day) {
        return String.format("%d-%02d-%02d", year, month, day);
    }

    //获取星期 一：1 二：2 ...
    public static int getDayOfWeekMonday(String time) {
        if (TextUtils.isEmpty(time)) return 1;
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        time = addZero(time);
        time = time.replace('-', '/');  //将2017-11-23 14:03:14  转换为符合要求的   2017/11/23 14:03:14
        time = time.replace('.', '/');  //将2017.11.23 14:03:14  转换为符合要求的   2017/11/23 14:03:14
        String[] split = time.split(" ");
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        Date d1;
        try {
            d1 = format.parse(split[0]);
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
        Calendar curCal = Calendar.getInstance();
        curCal.setFirstDayOfWeek(Calendar.MONDAY);
        assert d1 != null;
        curCal.setTime(d1);
        int dayOfWeek = curCal.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.SUNDAY)
            return 7;
        else
            return dayOfWeek - 1;
    }

    public static String getDayOfWeekMondayStr(String time) {
        int dayOfWeek = getDayOfWeekMonday(time);
        switch (dayOfWeek) {
            case 1:
                return "一";
            case 2:
                return "二";
            case 3:
                return "三";
            case 4:
                return "四";
            case 5:
                return "五";
            case 6:
                return "六";
            case 7:
                return "日";
        }
        return "";
    }

    /**
     * 返回日期信息
     *
     * @param date 2020/7/8 15:55:50
     * @return 返回数组： 年 月 日 时 分 秒 星期
     */
    public static int[] getDayInfo(String date) {
        if (TextUtils.isEmpty(date)) return new int[7];
        date = date.replace("-", "/");
        int[] dayInfo = new int[7];
        SimpleDateFormat format;
        if (date.contains(" "))
            format = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        else
            format = new SimpleDateFormat(YYYY_MM_DD);
        Date d;
        try {
            d = format.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
            return dayInfo;
        }
        Calendar sysCal = Calendar.getInstance();
        sysCal.setFirstDayOfWeek(Calendar.MONDAY);//西方周日为一周的第一天，咱得将周一设为一周第一天
        assert d != null;
        sysCal.setTime(d);
        dayInfo[0] = sysCal.get(Calendar.YEAR);
        dayInfo[1] = sysCal.get(Calendar.MONTH) + 1;
        dayInfo[2] = sysCal.get(Calendar.DAY_OF_MONTH);
        dayInfo[3] = sysCal.get(Calendar.HOUR_OF_DAY);
        dayInfo[4] = sysCal.get(Calendar.MINUTE);
        dayInfo[5] = sysCal.get(Calendar.SECOND);
        dayInfo[6] = sysCal.get(Calendar.DAY_OF_WEEK);
        dayInfo[6] = dayInfo[6] - 1;
        if(dayInfo[6] == 0){
            dayInfo[6] = 7;
        }
        return dayInfo;
    }

    /**
     * 返回日期信息
     *
     * @param date 2020/7/8 15:55:50
     * @return 返回数组： 年 月 日
     */
    public static int[] getDateInfo(String date) {
        if (TextUtils.isEmpty(date)) return new int[3];
        date = date.replace("-", "/");
        int[] dayInfo = new int[7];
        SimpleDateFormat format;
        if (date.contains(" "))
            format = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        else
            format = new SimpleDateFormat(YYYY_MM_DD);
        Date d;
        try {
            d = format.parse(date);
        } catch (Exception e) {
            return dayInfo;
        }
        Calendar sysCal = Calendar.getInstance();
        sysCal.setFirstDayOfWeek(Calendar.MONDAY);//西方周日为一周的第一天，咱得将周一设为一周第一天
        assert d != null;
        sysCal.setTime(d);
        dayInfo[0] = sysCal.get(Calendar.YEAR);
        dayInfo[1] = sysCal.get(Calendar.MONTH) + 1;
        dayInfo[2] = sysCal.get(Calendar.DAY_OF_MONTH);
        return dayInfo;
    }

    /**
     * 返回日期的月份
     */
    public static int getDayMonth(String date) {
        if (TextUtils.isEmpty(date)) return 0;
        date = date.replace("-", "/");
        String[] split = date.split("/");
        return Integer.parseInt(split[1]);
    }

    // 获取不包含日期的long类型时间 01:01:01  -->  3661
    public static int getLongTime(String time) {
        if (TextUtils.isEmpty(time)) return 0;
        if (time.contains(" "))
            time = time.substring(time.indexOf(" ") + 1);
        if (time.contains("."))
            time = time.substring(0, time.indexOf("."));
        int longTime = 0;
        String[] timeSplit = time.split(":");
        if (timeSplit.length == 3) {
            longTime = Integer.parseInt(timeSplit[0]) * 3600 + Integer.parseInt(timeSplit[1]) * 60 + Integer.parseInt(timeSplit[2]);
        } else if (timeSplit.length == 2) {
            longTime = Integer.parseInt(timeSplit[0]) * 60 + Integer.parseInt(timeSplit[1]);
        }
        return longTime;
    }

    /**
     * 判断该日期是否和当天是同一天
     * 先进行整个字符串的对比
     * 再进行年月日拆分并转换成int之后的对比
     * ----避免"04"和"4"这种情况的对比
     *
     * @param dateStr：格式为 yyyy/MM/dd
     */
    public static boolean isCurrentDay(String dateStr) {
        if (TextUtils.isEmpty(dateStr)) return false;
        if (dateStr.contains(" ")) dateStr = dateStr.split(" ")[0];
        dateStr = addZero(dateStr);
        dateStr = dateStr.replace('-', '/');
        String curDate = long2String(System.currentTimeMillis(), YYYY_MM_DD);
        if (dateStr.equals(curDate))
            return true;

        String[] dateArray = dateStr.split("/");
        String[] curDateArray = curDate.split("/");
        try {
            return Integer.parseInt(dateArray[0]) == Integer.parseInt(curDateArray[0]) &&
                    Integer.parseInt(dateArray[1]) == Integer.parseInt(curDateArray[1]) &&
                    Integer.parseInt(dateArray[2]) == Integer.parseInt(curDateArray[2]);
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static boolean isCurrentDay(long longTime) {
        if (longTime <= 0) return false;
        return isCurrentDay(long2String(longTime, YYYY_MM_DD));
    }

    /**
     * @param firstDate  第一天日期
     * @param secondDate 第二天日期
     * @return 是否是同一天
     */
    public static boolean isSameDay(String firstDate, String secondDate) {
        if (TextUtils.isEmpty(firstDate) || TextUtils.isEmpty(secondDate)) return false;
        if (firstDate.contains(" "))
            firstDate = firstDate.split(" ")[0];
        if (secondDate.contains(" "))
            secondDate = secondDate.split(" ")[0];
        firstDate = firstDate.replace('-', '/');
        secondDate = secondDate.replace('-', '/');
        return firstDate.equals(secondDate);
    }

    /**
     * @param firstDate  第一天日期
     * @param secondDate 第二天日期
     * @return 是否在同一年月
     */
    public static boolean isSameYearMonth(String firstDate, String secondDate) {
        if (TextUtils.isEmpty(firstDate) || TextUtils.isEmpty(secondDate)) return false;
        if (firstDate.contains(" "))
            firstDate = firstDate.split(" ")[0];
        if (secondDate.contains(" "))
            secondDate = secondDate.split(" ")[0];
        firstDate = firstDate.replace('-', '/');
        secondDate = secondDate.replace('-', '/');
        return firstDate.substring(0, firstDate.lastIndexOf("/"))
                .equals(secondDate.substring(0, firstDate.lastIndexOf("/")));
    }

    // 和系统时间对比，是否相差minute分钟
    public static boolean isInsideMinuteWithSystemTime(String preTime, int minute) {
        return isInsideMinute(preTime, long2String(System.currentTimeMillis(), YYYY_MM_DD_HH_MM_SS), minute);
    }

    /**
     * 判断curTime和preTime是否只相差5分钟
     * 格式：  2017/11/23 14:03:14
     *
     * @param preTime 上次时间
     * @param curTime 当前时间
     * @return 是否只相差5分钟
     */
    public static boolean isInsideMinute(String preTime, String curTime, int minute) {
        if (TextUtils.isEmpty(preTime) || TextUtils.isEmpty(curTime) || minute > 59 || minute < 0)
            return false;
        if (preTime.contains(".")) preTime = preTime.substring(0, preTime.indexOf("."));
        if (curTime.contains(".")) curTime = curTime.substring(0, curTime.indexOf("."));
        preTime = addZero(preTime);
        curTime = addZero(curTime);
        preTime = preTime.replace('-', '/');
        curTime = curTime.replace('-', '/');
        String[] curTimeSplit = curTime.split(" ");
        String[] preTimeSplit = preTime.split(" ");
        if (!preTimeSplit[0].equals(curTimeSplit[0])) return false;

        String[] curHMS = curTimeSplit[1].split(":");
        int curHour = Integer.parseInt(curHMS[0]);
        int curMin = Integer.parseInt(curHMS[1]);

        String[] preHMS = preTimeSplit[1].split(":");
        int preHour = Integer.parseInt(preHMS[0]);
        int preMin = Integer.parseInt(preHMS[1]);

        if (curHour == preHour) {
            return Math.abs(curMin - preMin) <= minute;
        } else if (Math.abs(curHour - preHour) > 1) {
            return false;
        } else {
            if (preHour > curHour)
                return 60 - curMin + preMin <= minute;
            else
                return 60 - preMin + curMin <= minute;
        }
    }

    public static int getTotalDayOfMonth(String date) {
        if (TextUtils.isEmpty(date)) return 0;
        date = date.replace('-', '/');
        date = date.split(" ")[0];
        String[] dateSplit = date.split("/");
        int year, month;
        try {
            year = Integer.parseInt(dateSplit[0]);
            month = Integer.parseInt(dateSplit[1]);
            return getTotalDayOfMonth(year, month);
        } catch (Exception ignored) {
            return 0;
        }
    }

    // 获取一个月有多少天
    public static int getTotalDayOfMonth(int year, int month) {
        int day = 30;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                // 1、非整百年份：能被4整除的是闰年。（如2004年就是闰年，2001年不是闰年）
                // 2、整百年份：能被400整除的是闰年。（如2000年是闰年，1900年不是闰年）
                if ((year % 100 != 0 && year % 4 == 0) || year % 400 == 0)
                    day = 29;
                else
                    day = 28;
                break;
        }
        return day;
    }

    public static int getTotalDayOfSeason(String date) {
        if (TextUtils.isEmpty(date)) return 0;
        date = date.replace('-', '/');
        date = date.split(" ")[0];
        String[] dateSplit = date.split("/");
        int year, month;
        try {
            year = Integer.parseInt(dateSplit[0]);
            month = Integer.parseInt(dateSplit[1]);
            return getTotalDayOfSeason(year, month);
        } catch (Exception ignored) {
            return 0;
        }
    }

    // 获取一季度有多少天
    public static int getTotalDayOfSeason(int year, int month) {
        if (month <= 10)
            return getTotalDayOfMonth(year, month) + getTotalDayOfMonth(year, month + 1)
                    + getTotalDayOfMonth(year, month + 2);
        if (month == 11)
            return 92;
        else
            return 62 + getTotalDayOfMonth(year + 1, 2);
    }

    public static int getTotalDayOfYear(String date) {
        if (TextUtils.isEmpty(date)) return 0;
        date = date.replace('-', '/');
        date = date.split(" ")[0];
        String[] dateSplit = date.split("/");
        int year;
        try {
            year = Integer.parseInt(dateSplit[0]);
            return getTotalDayOfYear(year);
        } catch (Exception ignored) {
            return 0;
        }
    }

    // 获取一年有多少天
    public static int getTotalDayOfYear(int year) {
        if ((year % 100 != 0 && year % 4 == 0) || year % 400 == 0)
            return 366;
        else
            return 365;
    }

    //获取指定日期和当前时间间隔多少天
    public static int getDayInterval(String time) {
        return getDayInterval(long2String(System.currentTimeMillis(), "yyyy/MM/dd"), time);
    }

    /**
     * 获取两个日期间隔多少天
     *
     * @return secondTime>=firstTime 返回正数 否则返回负数
     */
    public static int getDayInterval(String firstTime, String secondTime) {
        if (TextUtils.isEmpty(firstTime)) return 0;
        if (TextUtils.isEmpty(secondTime)) return 0;
        if (firstTime.contains(" "))
            firstTime = firstTime.split(" ")[0];
        firstTime = firstTime.replace("-", "/");
        if (secondTime.contains(" "))
            secondTime = secondTime.split(" ")[0];
        secondTime = secondTime.replace("-", "/");
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        try {
            Date date = format.parse(secondTime);
            Date currentDate = format.parse(firstTime);
            Calendar calendar = Calendar.getInstance();
            Calendar currentCalendar = Calendar.getInstance();
            assert date != null;
            assert currentDate != null;
            calendar.setTime(date);
            currentCalendar.setTime(currentDate);
            int year = calendar.get(Calendar.YEAR);
            int currentYear = currentCalendar.get(Calendar.YEAR);
            if (year > currentYear) {
                int totalDay = calendar.get(Calendar.DAY_OF_YEAR);
                for (int i = 0; i < year - currentYear; i++) {
                    if ((currentYear + i) % 4 == 0 && (currentYear + i) % 100 != 0 || (currentYear + i) % 400 == 0) {
                        totalDay += 366;
                    } else {
                        totalDay += 365;
                    }
                }
                totalDay -= currentCalendar.get(Calendar.DAY_OF_YEAR);
                return totalDay;
            } else if (year < currentYear) {
                int totalDay = currentCalendar.get(Calendar.DAY_OF_YEAR);
                for (int i = 0; i < currentYear - year; i++) {
                    if ((year + i) % 4 == 0 && (year + i) % 100 != 0 || (year + i) % 400 == 0) {
                        totalDay += 366;
                    } else {
                        totalDay += 365;
                    }
                }
                totalDay -= calendar.get(Calendar.DAY_OF_YEAR);
                return totalDay;
            } else {
                return calendar.get(Calendar.DAY_OF_YEAR) - currentCalendar.get(Calendar.DAY_OF_YEAR);
            }
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取两个日期间隔多少个月
     *
     * @return secondTime>=firstTime 返回正数 否则返回负数
     */
    public static int getMonthInterval(String firstTime, String secondTime) {
        if (TextUtils.isEmpty(firstTime)) return 0;
        if (TextUtils.isEmpty(secondTime)) return 0;
        if (firstTime.contains(" "))
            firstTime = firstTime.split(" ")[0];
        firstTime = firstTime.replace("-", "/");
        String[] firstTimeSplit = firstTime.split("/");
        if (secondTime.contains(" "))
            secondTime = secondTime.split(" ")[0];
        secondTime = secondTime.replace("-", "/");
        String[] secondTimeSplit = secondTime.split("/");
        int firstYear, firstMonth;
        int secondYear, secondMonth;
        try {
            firstYear = Integer.parseInt(firstTimeSplit[0]);
            firstMonth = Integer.parseInt(firstTimeSplit[1]);
            secondYear = Integer.parseInt(secondTimeSplit[0]);
            secondMonth = Integer.parseInt(secondTimeSplit[1]);
            if (secondYear == firstYear)
                return secondMonth - firstMonth;
            else
                return (secondYear - firstYear) * 12 + secondMonth - firstMonth;
        } catch (Exception ignored) {
            return 0;
        }
    }

    //获取上个月同一天的日期 2017/11/23 -> 2017/10/23
    public static String getPreMonthDay(String time) {
        if (TextUtils.isEmpty(time)) return "";
        time = time.replace('-', '/');  //将2017-11-23 14:03:14  转换为符合要求的   2017/11/23 14:03:14
        if (time.contains(" "))
            time = time.substring(0, time.indexOf(" ")); //只获取日期 2017/11/23
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        try {
            Date date = format.parse(time);
            Calendar calendar = Calendar.getInstance();
            assert date != null;
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, -1);
            return format.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            return time;
        }
    }

    // 根据给的日期信息，获取前一天日期
    public static int[] getPreDateInfo(int[] dateInfo) {
        int[] preDateInfo = new int[3];
        int day = dateInfo[2];
        int month = dateInfo[1];
        int year = dateInfo[0];

        if (day > 1) {
            preDateInfo[0] = year;
            preDateInfo[1] = month;
            preDateInfo[2] = day - 1;
        } else {
            if (month > 1) {
                preDateInfo[0] = year;
                preDateInfo[1] = month - 1;
                preDateInfo[2] = TimeUtils.getTotalDayOfMonth(year, preDateInfo[1]);
            } else {
                preDateInfo[0] = year - 1;
                preDateInfo[1] = 12;
                preDateInfo[2] = 31;
            }
        }
        return preDateInfo;
    }

    // 获取上一周的周一和周日的日期
    public static String[] getLastWeekFirstAndLastDay(Date date) {
        String[] lastData = new String[2];
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.setFirstDayOfWeek(Calendar.MONDAY);
        calendar2.setFirstDayOfWeek(Calendar.MONDAY);
        calendar1.setTime(date);
        calendar2.setTime(date);
        int dayOfWeek = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
        int offset1 = 1 - dayOfWeek;
        int offset2 = 7 - dayOfWeek;
        calendar1.add(Calendar.DATE, offset1 - 7);
        calendar2.add(Calendar.DATE, offset2 - 7);
        // last Monday
        lastData[0] = sdf.format(calendar1.getTime());
        // last Sunday
        lastData[1] = sdf.format(calendar2.getTime());
        return lastData;
    }

    // 当前日期加上hour小时
    public static String addHour(String date, int hour) {
        boolean isHorizontalLine = date.contains("-");
        if (isHorizontalLine)
            date = date.replace("-", "/");
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(string2Long(date));
        cal.add(Calendar.HOUR_OF_DAY, hour);
        String nextDate = dateFormat.format(cal.getTime());
        if (isHorizontalLine)
            return nextDate.replace("/", "-");
        else
            return nextDate;
    }

    // 当前日期加上day天
    public static String addDay(String date, int day) {
        boolean isHorizontalLine = date.contains("-");
        if (isHorizontalLine)
            date = date.replace("-", "/");
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat;
        if (date.contains(" "))
            dateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        else
            dateFormat = new SimpleDateFormat(YYYY_MM_DD);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(string2Long(date));
        cal.add(Calendar.DATE, day);
        String nextDate = dateFormat.format(cal.getTime());
        if (isHorizontalLine)
            return nextDate.replace("/", "-");
        else
            return nextDate;
    }

    // 获取这一天所在的这一周所有日期
    public static List<String> getWeekDayList(String date) {
        List<String> weekMillisList = new ArrayList<>();
        int dayOfWeekMonday = getDayOfWeekMonday(date);

        boolean isHorizontalLine = date.contains("-");
        if (isHorizontalLine)
            date = date.replace("-", "/");
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(string2Long(date));

        if (dayOfWeekMonday == 1)
            weekMillisList.add(date);
        else {
            cal.add(Calendar.DATE, 1 - dayOfWeekMonday);
            weekMillisList.add(dateFormat.format(cal.getTime()));
        }
        for (int i = 1; i < 7; i++) {
            cal.add(Calendar.DATE, 1);
            weekMillisList.add(dateFormat.format(cal.getTime()));
        }
        return weekMillisList;
    }

    public static List<String[]> getWeekListOfYear(int year) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD);
        int totalDayOfYear = getTotalDayOfYear(year);
        String firstDate = String.format(Locale.getDefault(), "%d/01/01", year);
        int firstDateWeek = getDayOfWeekMonday(firstDate);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(string2Long(firstDate));
        if (firstDateWeek != 1) {
            totalDayOfYear -= (8 - firstDateWeek);
            calendar.add(Calendar.DATE, 8 - firstDateWeek);
        }
        int totalWeeks = totalDayOfYear % 7 == 0 ? totalDayOfYear / 7 : totalDayOfYear / 7 + 1;
        List<String[]> result = new ArrayList<>();
        String[] weekDate;
        for (int i = 0; i < totalWeeks; i++) {
            weekDate = new String[2];
            weekDate[0] = dateFormat.format(calendar.getTime()); // 星期一
            calendar.add(Calendar.DATE, 6);
            weekDate[1] = dateFormat.format(calendar.getTime()); // 星期天
            calendar.add(Calendar.DATE, 1);
            result.add(weekDate);
        }
        return result;
    }

    public static List<String[]> getWeekListOfYear(int startYear, int endYear) {
        L.i("getWeekListOfYear start");
        List<String[]> result = new ArrayList<>();
        for (; startYear <= endYear; startYear++) {
            result.addAll(getWeekListOfYear(startYear));
            L.i("getWeekListOfYear start get: " + startYear);
        }
        return result;
    }
    // endregion

    // region 转换
    public static String deleteZero(String dateTime) {
        if (TextUtils.isEmpty(dateTime)) return dateTime;
        String[] split = dateTime.split(" ");
        String[] splitDate = split[0].replace("-", "/").split("/");
        if (splitDate.length < 3) return dateTime;
        String date = String.format(Locale.getDefault(), "%s/%d/%d", splitDate[0],
                Integer.parseInt(splitDate[1]), Integer.parseInt(splitDate[2]));
        return split.length == 2 ? date + " " + split[1] : date;
    }

    /**
     * 为时间加上0
     * 避免String类型使用equal判断时因为0而导致失败的情况
     * 在每个方法最前面添加进行转换，保证格式统一
     *
     * @param time 当前时间 格式： 2017/4/23 14:3:14
     * @return 2017/04/23 14:03:14
     */
    private static String addZero(String time) {
        String[] dateAndTime = time.split(" ");
        String date = addZeroForDate(dateAndTime[0]);
        if (dateAndTime.length == 1)
            return date;

        String[] timePart = dateAndTime[1].split(":");
        if (Integer.parseInt(timePart[0]) < 10)
            timePart[0] = String.valueOf(0) + Integer.valueOf(timePart[0]);
        if (Integer.parseInt(timePart[1]) < 10)
            timePart[1] = String.valueOf(0) + Integer.valueOf(timePart[1]);
        if (Integer.parseInt(timePart[2]) < 10)
            timePart[2] = String.valueOf(0) + Integer.valueOf(timePart[2]);
        return date + " " + timePart[0] + ":" + timePart[1] + ":" + timePart[2];
    }

    /**
     * 为年月日加上0
     * 避免String类型使用equal判断时因为0而导致失败的情况
     * 在每个方法最前面添加进行转换，保证格式统一
     *
     * @param date 当前时间 格式： 2017/4/23
     * @return 2017/04/23
     */
    private static String addZeroForDate(String date) {
        date = date.replace('-', '/');
        String[] datePart = date.split("/");
        if (Integer.parseInt(datePart[1]) < 10)
            datePart[1] = String.valueOf(0) + Integer.valueOf(datePart[1]);
        if (Integer.parseInt(datePart[2]) < 10)
            datePart[2] = String.valueOf(0) + Integer.valueOf(datePart[2]);
        return datePart[0] + '/' + datePart[1] + '/' + datePart[2];
    }

    /**
     * 将长整型数字转换为日期格式的字符串
     */
    public static String long2String(long time) {
        return long2String(time, YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 将长整型数字转换为日期格式的字符串
     */
    public static String long2String(long time, String format) {
        if (null == format)
            format = YYYY_MM_DD_HH_MM_SS;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(time));
    }

    /**
     * 将日期格式的字符串转换为长整型
     */
    public static long string2Long(String date) {
        if (TextUtils.isEmpty(date)) return 0;
        date = date.replace("-", "/");
        String[] split = date.split(":");
        if (split.length == 1) {
            return string2Long(date, YYYY_MM_DD);
        } else if (split.length == 2) {
            return string2Long(date, YYYY_MM_DD_HH_MM);
        } else if (split.length == 3) {
            return string2Long(date, YYYY_MM_DD_HH_MM_SS);
        } else
            return 0;
    }

    /**
     * 将日期格式的字符串转换为长整型
     */
    public static long string2Long(String date, String format) {
        SimpleDateFormat sf = new SimpleDateFormat(format);
        try {
            return Objects.requireNonNull(sf.parse(date)).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 将秒转换成时间格式 --> 3679    01:01:19
     */
    @SuppressLint("DefaultLocale")
    public static String secondToTime(int second) {
        if (second < 60) return String.format("00:%02d", second);
        else if (second < 3600) {
            int minute = second / 60;
            second %= 60;
            return String.format("%02d:%02d", minute, second);
        } else {
            int hour = second / 3600;
            second %= 3600;
            int minute = second / 60;
            second %= 60;
            return String.format("%02d:%02d:%02d", hour, minute, second);
        }
    }

    /**
     * 获取time与当前时间的间隔，返回long类型
     */
    public static long getTimeInterval(String time) {
        if (TextUtils.isEmpty(time)) return 0;
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        time = time.replace('-', '/');
        return System.currentTimeMillis() - string2Long(time, YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 如果是当天：则得到当前时间的时分
     * 如果不是：则得到当前时间的月日时分
     *
     * @param time 当前时间 格式： 2017/11/23 14:03:14
     * @return isCurrentDay true --> 14:03
     * false--> isCurrentYear true-->11月23日 14:03  false-->2017年11月23日 14:03
     */
    public static String getShortTime(String time) {
        if (TextUtils.isEmpty(time)) return "";
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        time = addZero(time);
        time = time.replace('-', '/');  //将2017-11-23 14:03:14  转换为符合要求的   2017/11/23 14:03:14
        if (isCurrentDay(time.substring(0, time.indexOf(" "))))
            return time.substring(time.indexOf(' ') + 1, time.lastIndexOf(':'));

        String curDate = long2String(System.currentTimeMillis(), YYYY_MM_DD);
        String[] split = time.split(" ");
        String[] date = split[0].split("/");
        String shortTime = date[1] + "月" + date[2] + "日" + " " + split[1].substring(0, split[1].lastIndexOf(':'));

        String curYear = curDate.substring(0, curDate.indexOf('/'));
        String timeYear = time.substring(0, time.indexOf('/'));
        if (!curYear.equals(timeYear))
            shortTime = timeYear + "年" + shortTime;
        return shortTime;
    }

    /**
     * 如果是当天：则得到当前时间的时分
     * 如果是当前年份，则得到当前时间的月日
     * 如果不是：则得到当前时间的年月日
     *
     * @param time 当前时间 格式： 2017/11/23 14:03:14
     * @return isCurrentDay true --> 14:03
     * false--> isCurrentYear true-->11月23日  false-->2017年11月23日
     */
    public static String getShortDateOrTime(String time) {
        if (TextUtils.isEmpty(time)) return "";
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        time = addZero(time);
        time = time.replace('-', '/');  //将2017-11-23 14:03:14  转换为符合要求的   2017/11/23 14:03:14
        if (isCurrentDay(time.substring(0, time.indexOf(" "))))
            return time.substring(time.indexOf(' ') + 1, time.lastIndexOf(':'));

        String curDate = long2String(System.currentTimeMillis(), YYYY_MM_DD);
        String[] split = time.split(" ");
        String[] date = split[0].split("/");
        String shortTime = date[1] + "月" + date[2] + "日";

        String curYear = curDate.substring(0, curDate.indexOf('/'));
        String timeYear = time.substring(0, time.indexOf('/'));
        if (!curYear.equals(timeYear)) {
            shortTime = timeYear + "年" + shortTime;
        }
        return shortTime;
    }

    /**
     * 不是当前年份则返回年
     * 不是当天则返回空字符串
     * 当天：
     * 1：1分钟内显示 刚刚
     * 2：1分钟后-1小时内，显示 xx分钟前
     * 3：1小时后-24小时内，显示 xx小时前
     */
    public static String getTimeFormat(String time) {
        if (TextUtils.isEmpty(time)) return "";
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        time = addZero(time);
        time = time.replace('-', '/');  //将2017-11-23 14:03:14  转换为符合要求的   2017/11/23 14:03:14

        String curDate = long2String(System.currentTimeMillis(), YYYY_MM_DD);

        String[] split = time.split(" ");
        String[] curSplit = curDate.split(" ");

        String[] dateSplit = split[0].split("/");
        String[] curDateSplit = curSplit[0].split("/");

        if (!dateSplit[0].equals(curDateSplit[0])) {
            //显示年
            return dateSplit[0];
        } else if (!dateSplit[1].equals(curDateSplit[1]) ||
                !dateSplit[2].equals(curDateSplit[2])) {
            return "";
        } else {
            long timeInterval = getTimeInterval(time) / 1000; //转成秒
            // 一小时3600秒
            if (timeInterval > 3600 * 24) {
                return "";
                //显示 时:分
//                return split[1].substring(0, split[1].lastIndexOf(":"));
            } else if (timeInterval >= 3600) {
                //显示 xx小时前
                return String.format(Locale.getDefault(), "%d小时前", timeInterval / 3600);
            } else if (timeInterval >= 60) {
                //显示 xx分钟前
                return String.format(Locale.getDefault(), "%d分钟前", timeInterval / 60);
            } else {
                return "刚刚";
            }
        }
    }

    /**
     * 直接拼接时间的年月日时分秒
     *
     * @param time 当前时间 格式： 2017/11/23 14:03:14
     * @return 20171123140314
     */
    public static String stitchingTime(String time) {
        if (TextUtils.isEmpty(time)) return "";
        if (time.split(" ").length < 2) return time;
        time = addZero(time);
        time = time.replace('-', '/');
        String[] split = time.split(" ");
        String[] date = split[0].split("/");
        String[] dateTime = split[1].split(":");
        return date[0] + date[1] + date[2] + dateTime[0] + dateTime[1] + dateTime[2];
    }

    /**
     * 解析复原时间
     *
     * @param stitchingTime 当前时间 格式： 20171123140314
     * @return 2017-11-23 14:03:14
     */
    public static String revertTime(String stitchingTime) {
        if (TextUtils.isEmpty(stitchingTime) || stitchingTime.length() < 14) return "";
        return stitchingTime.substring(0, 4) + "-" + stitchingTime.substring(4, 6) + "-" + stitchingTime.substring(6, 8) + " " +
                stitchingTime.substring(8, 10) + ":" + stitchingTime.substring(10, 12) + ":" + stitchingTime.substring(12);
    }

    /**
     * 对比两个时间的大小
     *
     * @return 第一个时间更大返回大于0
     * 第二个时间更大返回小于0
     * 相等返回0
     */
    public static int compareTime(String firstTime, String secondTime) {
        if (TextUtils.isEmpty(firstTime) || TextUtils.isEmpty(secondTime)) return 0;
        if (firstTime.contains(".")) firstTime = firstTime.substring(0, firstTime.indexOf("."));
        if (secondTime.contains(".")) secondTime = secondTime.substring(0, secondTime.indexOf("."));
        String fTime = firstTime.replace('-', '/');
        String sTime = secondTime.replace('-', '/');
        long firstLongTime = string2Long(fTime, fTime.contains(" ") ? YYYY_MM_DD_HH_MM_SS : YYYY_MM_DD);
        long secondLongTime = string2Long(sTime, sTime.contains(" ") ? YYYY_MM_DD_HH_MM_SS : YYYY_MM_DD);
        return Long.compare(firstLongTime, secondLongTime);
    }

    /**
     * 在原来时间的基础上加上1秒
     */
    public static String addOneSecond(String time) {
        if (TextUtils.isEmpty(time)) return "";
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        String replace = time.replace('-', '/');
        long longTime = string2Long(replace, YYYY_MM_DD_HH_MM_SS);
        return long2String(longTime + 1000, YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * @param time 当前时间 格式： 2017/11/23 14:03:14
     * @return isCurrentDay true --> 14:03
     * false --> 是否是昨天 true --> 昨天14:03
     * false --> 是否是前天 true --> 前天14:03
     * false --> 是否是同一个星期 true --> 星期一14:03
     * false --> isCurrentYear true --> 11月23日
     * false --> 2017年11月23日
     */
    public static String convertTime(String time) {
        if (TextUtils.isEmpty(time)) return "";
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        time = addZero(time);
        time = time.replace('-', '/');  //将2017-11-23 14:03:14  转换为符合要求的   2017/11/23 14:03:14
        if (isCurrentDay(time.substring(0, time.indexOf(" "))))
            return time.substring(time.indexOf(' ') + 1, time.lastIndexOf(':'));

        String[] split = time.split(" ");
        String[] date = split[0].split("/");
        //月日去掉小于10时的首位0
        if (date[1].charAt(0) == '0')
            date[1] = date[1].substring(1);
        if (date[2].charAt(0) == '0')
            date[2] = date[2].substring(1);
        String[] detailTime = split[1].split(":");
        String curTime = long2String(System.currentTimeMillis(), YYYY_MM_DD);

        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        Date d1;
        Date d2;
        try {
            d1 = format.parse(split[0]);
            d2 = format.parse(curTime);
        } catch (Exception e) {
            e.printStackTrace();
            return getShortTime(time);
        }
        Calendar sysCal = Calendar.getInstance();
        Calendar curCal = Calendar.getInstance();
        sysCal.setFirstDayOfWeek(Calendar.MONDAY);//西方周日为一周的第一天，咱得将周一设为一周第一天
        curCal.setFirstDayOfWeek(Calendar.MONDAY);
        assert d1 != null;
        sysCal.setTime(d1);
        assert d2 != null;
        curCal.setTime(d2);

        if (curCal.get(Calendar.YEAR) != sysCal.get(Calendar.YEAR)) {
            return String.format("%s年%s月%s日", date[0], date[1], date[2]);
        } else {
            if (curCal.get(Calendar.DAY_OF_YEAR) - sysCal.get(Calendar.DAY_OF_YEAR) > 2) {
                if (curCal.get(Calendar.WEEK_OF_YEAR) == sysCal.get(Calendar.WEEK_OF_YEAR)) {
                    String dayOfWeek = "";
                    int i = sysCal.get(Calendar.DAY_OF_WEEK);
                    switch (i) {
                        case Calendar.MONDAY:
                            dayOfWeek = "星期一";
                            break;
                        case Calendar.TUESDAY:
                            dayOfWeek = "星期二";
                            break;
                        case Calendar.WEDNESDAY:
                            dayOfWeek = "星期三";
                            break;
                        case Calendar.THURSDAY:
                            dayOfWeek = "星期四";
                            break;
                        case Calendar.FRIDAY:
                            dayOfWeek = "星期五";
                            break;
                        case Calendar.SATURDAY:
                            dayOfWeek = "星期六";
                            break;
                        case Calendar.SUNDAY:
                            dayOfWeek = "星期日";
                            break;
                    }
                    return String.format("%s %s:%s", dayOfWeek, detailTime[0], detailTime[1]);
                } else {
                    return String.format("%s月%s日", date[1], date[2]);
                }
            } else {
                if (curCal.get(Calendar.DAY_OF_YEAR) - sysCal.get(Calendar.DAY_OF_YEAR) == 2) {
                    return String.format("前天 %s:%s", detailTime[0], detailTime[1]);
                } else {
                    return String.format("昨天 %s:%s", detailTime[0], detailTime[1]);
                }
            }
        }
    }

    /**
     * @param time 当前时间 格式： 2017/11/23 14:03:14
     * @return isCurrentDay true --> 14:03
     * false --> 是否是昨天 true --> 昨天
     * false --> 是否是前天 true --> 前天
     * false --> 是否是同一个星期 true --> 星期一
     * false --> isCurrentYear true --> 11月23日
     * false --> 2017年11月23日
     */
    public static String convertDateOrTime(String time) {
        if (TextUtils.isEmpty(time)) return "";
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        time = addZero(time);
        time = time.replace('-', '/');  //将2017-11-23 14:03:14  转换为符合要求的   2017/11/23 14:03:14
        if (isCurrentDay(time.substring(0, time.indexOf(" "))))
            return time.substring(time.indexOf(' ') + 1, time.lastIndexOf(':'));

        String[] split = time.split(" ");
        String[] date = split[0].split("/");
        //月日去掉小于10时的首位0
        if (date[1].charAt(0) == '0')
            date[1] = date[1].substring(1);
        if (date[2].charAt(0) == '0')
            date[2] = date[2].substring(1);
        String curTime = long2String(System.currentTimeMillis(), YYYY_MM_DD);

        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        Date d1;
        Date d2;
        try {
            d1 = format.parse(split[0]);
            d2 = format.parse(curTime);
        } catch (Exception e) {
            e.printStackTrace();
            return time;
        }
        Calendar sysCal = Calendar.getInstance();
        Calendar curCal = Calendar.getInstance();
        sysCal.setFirstDayOfWeek(Calendar.MONDAY);//西方周日为一周的第一天，咱得将周一设为一周第一天
        curCal.setFirstDayOfWeek(Calendar.MONDAY);
        assert d1 != null;
        sysCal.setTime(d1);
        assert d2 != null;
        curCal.setTime(d2);

        if (curCal.get(Calendar.YEAR) != sysCal.get(Calendar.YEAR)) {
            return String.format("%s年%s月%s日", date[0], date[1], date[2]);
        } else {
            if (curCal.get(Calendar.DAY_OF_YEAR) - sysCal.get(Calendar.DAY_OF_YEAR) > 2) {
                if (curCal.get(Calendar.WEEK_OF_YEAR) == sysCal.get(Calendar.WEEK_OF_YEAR)) {
                    String dayOfWeek = "";
                    int i = sysCal.get(Calendar.DAY_OF_WEEK);
                    switch (i) {
                        case Calendar.MONDAY:
                            dayOfWeek = "星期一";
                            break;
                        case Calendar.TUESDAY:
                            dayOfWeek = "星期二";
                            break;
                        case Calendar.WEDNESDAY:
                            dayOfWeek = "星期三";
                            break;
                        case Calendar.THURSDAY:
                            dayOfWeek = "星期四";
                            break;
                        case Calendar.FRIDAY:
                            dayOfWeek = "星期五";
                            break;
                        case Calendar.SATURDAY:
                            dayOfWeek = "星期六";
                            break;
                        case Calendar.SUNDAY:
                            dayOfWeek = "星期日";
                            break;
                    }
                    return dayOfWeek;
                } else {
                    return String.format("%s月%s日", date[1], date[2]);
                }
            } else {
                if (curCal.get(Calendar.DAY_OF_YEAR) - sysCal.get(Calendar.DAY_OF_YEAR) == 2) {
                    return "前天";
                } else {
                    return "昨天";
                }
            }
        }
    }

    /**
     * @param time 当前时间 格式： 2017/11/23 或者 2017/11/23 14:03:14
     * @return isCurrentDay true --> 今天
     * false --> 是否是昨天 true --> 昨天
     * false --> isCurrentYear true --> 11月23日
     * false --> 2017年11月23日
     */
    public static String convertDate(String time) {
        if (TextUtils.isEmpty(time)) return "";
        if (time.contains(" "))
            time = time.substring(0, time.indexOf(" "));
        if (time.contains(".")) time = time.substring(0, time.indexOf("."));
        time = addZero(time);
        time = time.replace('-', '/');  //将2017-11-23 14:03:14  转换为符合要求的   2017/11/23 14:03:14
        if (isCurrentDay(time))
            return "今天";

        String[] date = time.split("/");
        //月日去掉小于10时的首位0
        if (date[1].charAt(0) == '0')
            date[1] = date[1].substring(1);
        if (date[2].charAt(0) == '0')
            date[2] = date[2].substring(1);
        String curTime = long2String(System.currentTimeMillis(), YYYY_MM_DD);

        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        Date d1;
        Date d2;
        try {
            d1 = format.parse(time);
            d2 = format.parse(curTime);
        } catch (Exception e) {
            e.printStackTrace();
            return time;
        }
        Calendar sysCal = Calendar.getInstance();
        Calendar curCal = Calendar.getInstance();
        sysCal.setFirstDayOfWeek(Calendar.MONDAY);//西方周日为一周的第一天，咱得将周一设为一周第一天
        curCal.setFirstDayOfWeek(Calendar.MONDAY);
        assert d1 != null;
        sysCal.setTime(d1);
        assert d2 != null;
        curCal.setTime(d2);

        if (curCal.get(Calendar.YEAR) != sysCal.get(Calendar.YEAR)) {
            return String.format("%s年%s月%s日", date[0], date[1], date[2]);
        } else {
            if (curCal.get(Calendar.DAY_OF_YEAR) - sysCal.get(Calendar.DAY_OF_YEAR) == 1) {
                return "昨天";
            } else {
                return String.format("%s月%s日", date[1], date[2]);
            }
        }
    }

    /**
     * 将时长转换成分钟，舍弃日期和秒，只计算小时和分钟
     */
    public static int stringToMinute(String time) {
        if (TextUtils.isEmpty(time)) return 0;
        else {
            int minute;
            if (time.contains(" "))
                time = time.split(" ")[1];
            String[] timeSplit = time.split(":");
            try {
                minute = Integer.parseInt(timeSplit[0]) * 60 + Integer.parseInt(timeSplit[1]);
            } catch (Exception e) {
                return 0;
            }
            return minute;
        }
    }

    /**
     * 将时间转成 日时分秒
     *
     * @param time 单位s
     * @return 长度为4的数组  日 时 分 秒
     * 例如90066 -> [1,1,1,6]
     * 1天86400秒 + 1小时3600秒 + 1分钟60秒 + 6秒
     */
    public static long[] convertDayInfo(long time) {
        long[] dayInfo = new long[4];
        dayInfo[3] = time % 60;
        time = time / 60;
        if (time > 0) {
            dayInfo[2] = time % 60;
            time = time / 60;
            if (time > 0) {
                dayInfo[1] = time % 24;
                time = time / 24;
                dayInfo[0] = time;
            }
        }
        return dayInfo;
    }
    // endregion
}
